package com.miplus.ccrm.core.service.action;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.miplus.ccrm.common.*;
import com.miplus.ccrm.core.controller.vo.action.*;
import com.miplus.ccrm.core.controller.vo.aicall.ObCallListResVo;
import com.miplus.ccrm.core.mapper.*;
import com.miplus.ccrm.core.pojo.*;
import com.miplus.ccrm.core.security.JCommonData;
import com.miplus.ccrm.core.service.ExportService;
import com.miplus.ccrm.core.service.collect.FiImportHistService;
import com.miplus.ccrm.core.service.collect.FiTaskService;
import com.miplus.ccrm.core.service.strategy.CpCalllistService;
import com.miplus.ccrm.core.utils.EnumFiChannel;
import com.miplus.ccrm.sms.JSmsService;
import com.miplus.ccrm.sms.SmsR;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

/**
* @author pc
* @description 针对表【sms_sendphn】的数据库操作Service实现
* @createDate 2024-04-25 20:29:32
*/
@Slf4j
@Service
public class SmsSendphnServiceImpl extends MPJBaseServiceImpl<SmsSendphnMapper, SmsSendphn>
    implements SmsSendphnService{
    @Resource
    private FiTaskService fiTaskService;
    @Resource
    private ConContactMapper conContactMapper;
    @Resource
    private MsgDefineMapper msgDefineMapper;
    @Resource
    private JSmsService smsService;
    @Resource
    private CpCalllistService cpCalllistService;
    @Resource
    private ExportService exportService;
    @Resource
    private FiImportHistService fiImportHistService;
    @Resource
    private FiCreditcasesMapper fiCreditcasesMapper;

    @Override
    public IPage<SmsResVo> fiSmsList(String $usrid, SmsReqVo paras)
    {
        return selectJoinListPage(new Page<>(paras.getPageNum(), paras.getPageSize()),
                SmsResVo.class,
                new MPJLambdaWrapper<SmsSendphn>()
                        .selectAs("fun_getnames('SMS.STATUS',t.status)",SmsResVo::getStatus)
                        .selectAs(String.format("fi_starSecu('%s','disstar.phone',t.phn,'')",$usrid), SmsResVo::getPhn)
                        .select(SmsSendphn::getCrdt,SmsSendphn::getMsg,SmsSendphn::getSmslevel,SmsSendphn::getErrcode,
                                SmsSendphn::getCause,SmsSendphn::getCrmid,SmsSendphn::getUsrid,SmsSendphn::getMsgid,SmsSendphn::getAppid)
                        .eq(JPubUtils.IsNotEmpty(paras.getUsrid()), SmsSendphn::getUsrid,paras.getUsrid())
                        .eq(JPubUtils.IsNotEmpty(paras.getStatus()),SmsSendphn::getStatus,paras.getStatus())
                        .between(JPubUtils.IsNotEmpty(paras.getStartdt()), SmsSendphn::getCrdt,JPubUtils.StringToDate(paras.getStartdt()),JPubUtils.StringToDate(paras.getEnddt()))
                        .orderByAsc(SmsSendphn::getKid)
        );
    }

    @Override
    public CmdResVo fiSmsAdd(String $usrid, SmsAddVo paras)
    {
        //联系人是为了客户端不送明码电话过来，后台取表关联数据
        if(JPubUtils.IsEmpty(paras.getContactnumber())&&
                JPubUtils.IsEmpty(paras.getPhone())){
            throw new ServiceException(EnumRCode.ArgErr.value, EnumRCode.ArgErr.name);
        }

        MsgDefine define=msgDefineMapper.selectById(paras.getMsgid());
        if(define==null) {
            throw new ServiceException(EnumRCode.NoFindTemp.value, EnumRCode.NoFindTemp.name);
        }
        String tempid=define.getTitle();
        String smstype=define.getUrl();

        String phone=paras.getPhone();
        //如果有联系人ID，优先以联系人为准
        if(JPubUtils.IsNotEmpty(paras.getContactnumber())){
          ConContact contact=conContactMapper.selectById(paras.getContactnumber());
          phone=contact.getPhone();
        }
        String clid=paras.getClid();
        if(JPubUtils.IsEmpty(clid)){
            clid="SYS_SMS";
        }
        Integer tasknumber=0;
        String smstxt=paras.getSmstext().trim();
        if(JPubUtils.IsNotEmpty(paras.getFicaseid())) {
            cpCalllistService.checkActionOk(paras.getFicaseid(),clid,EnumFiChannel.Sms);
            tasknumber=fiTaskService.addTask($usrid, clid, paras.getFicaseid(),EnumFiChannel.Sms.value,
                    paras.getContactnumber(),phone,"WAITSEND",smstxt);
        }

        String ipaddr=JPubUtils.getLocalIpAddr();
        SmsR smsR=smsService.SendSms(ipaddr,tempid,smstype,phone,smstxt);

        if(smsR.getCode()==0){
            SaveSms(phone,smstxt,paras.getMsgid(),tasknumber,smstype,$usrid,2,"0", smsR.getRefID());
        }
        else{
            SaveSms(phone,smstxt,paras.getMsgid(),tasknumber,smstype,$usrid,3,smsR.getCode().toString(),"");
            throw new ServiceException(EnumRCode.CmdFail.value, "SmsFail:"+smsR.getCode().toString());
        }

        return new CmdResVo(0,"1");
    }

    @Override
    public CmdResVo fiSmsSendCode(String usrid, JCommonData jCommonData)
    {
        String mobile=baseMapper.getUsrMobile(usrid);
        if(JPubUtils.IsEmpty(mobile)){
            throw new ServiceException(EnumRCode.NoFindMobile.value, EnumRCode.NoFindMobile.name);
        }
        String msgid="SMS_VCODE";
        MsgDefine define=msgDefineMapper.selectById(msgid);
        if(define==null) {
            throw new ServiceException(EnumRCode.NoFindTemp.value, EnumRCode.NoFindTemp.name);
        }
        String smstxt=define.getSmstxt();
        String tempid=define.getTitle();
        String smstype=define.getUrl();
        Random rand=new Random();
        Integer num=rand.nextInt(900000)+100000;
        String sendtxt=smstxt.replace("{CODE}",num.toString());
        sendtxt=sendtxt.replace("{code}",num.toString());

        String ipaddr=JPubUtils.getLocalIpAddr();
        SmsR smsR=smsService.SendSms(ipaddr,tempid,smstype,mobile,sendtxt);

        if(smsR.getCode()==0){
            jCommonData.SetUsrSmsVCode(usrid, num.toString());
            SaveSms(mobile,sendtxt,msgid,0,smstype,usrid,2,"0", smsR.getRefID());
        }
        else{
            SaveSms(mobile,sendtxt,msgid,0,smstype,usrid,3,smsR.getCode().toString(),"");
            throw new ServiceException(EnumRCode.CmdFail.value, "SmsFail:"+smsR.getCode().toString());
        }

        return new CmdResVo(1);
    }

    private int SaveSms(String phone,String smstxt,String msgid,Integer tasknumber,
                        String appid,String usrid,Integer status,String code,String refId)
    {
        SmsSendphn sms=new SmsSendphn();
        sms.setPhn(phone);
        sms.setMsg(smstxt);
        sms.setMsgid(msgid);
        if(tasknumber>0) {
            sms.setCrmid(tasknumber.toString());
        }
        sms.setStatus(status); //1=待发送,2=成功，3=失败
        if(status==3){
            sms.setErrcode(code);
            sms.setCause("Fail");
        }else{
            sms.setErrcode("0");
            sms.setCause("Success");
            sms.setRefid(refId);
        }
        sms.setAppid(appid);
        sms.setSmslevel(100);
        sms.setCrdt(new Date());
        sms.setSenddt(new Date());
        sms.setUsrid(usrid);

        return baseMapper.insert(sms);
    }

    @Override
    public CmdResVo expSmsList(JSysUser user, SmsReqVo paras, HttpServletResponse response)
    {
        String $usrid = user.getUsrid();
        int pagesize = paras.getPageSize();
        if (pagesize > JPubUtils.exportMaxCount) {
            paras.setPageSize(JPubUtils.exportMaxCount);
        }
        log.info("expSmsList:pagesize={}",pagesize);

        IPage<SmsResVo> pages=fiSmsList(user.getUsrid(),paras);
        ArrayList arr=new ArrayList();

        String exptempid=JPubUtils.getExpTempID(paras.getExpfilename(),"短信发送数据");
        String filename=JPubUtils.getExpFileName(
                paras.getExpfilename(),exptempid
        );
        pages.convert(u->{
            HashMap map=JPubUtils.toExportMap(u);
            if(map!=null) arr.add(map);
            return u;
        });
        CmdResVo resVo=exportService.ToExcel(
                response,
                arr,
                paras.getExpidlist(),
                paras.getExpnamelist(),
                filename,
                $usrid
        );

        int okcount=resVo.getCount();
        if(okcount>0){
            fiImportHistService.AddExportHist(
                    resVo.getKeyId(),
                    $usrid,
                    exptempid,
                    filename,
                    okcount
            );
        }
        arr.clear();

        return resVo;
    }
}




